/**
 * T模板
 */
(function(){function c(a){this.t=a}function l(a,b){for(var e=b.split(".");e.length;){if(!(e[0]in a))return!1;a=a[e.shift()]}return a}function d(a,b){return a.replace(h,function(e,a,i,f,c,h,k,m){var f=l(b,f),j="",g;if(!f)return"!"==i?d(c,b):k?d(m,b):"";if(!i)return d(h,b);if("@"==i){e=b._key;a=b._val;for(g in f)f.hasOwnProperty(g)&&(b._key=g,b._val=f[g],j+=d(c,b));b._key=e;b._val=a;return j}}).replace(k,function(a,c,d){return(a=l(b,d))||0===a?"%"==c?(new Option(a)).innerHTML.replace(/"/g,"&quot;"):
a:""})}var h=/\{\{(([@!]?)(.+?))\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g,k=/\{\{([=%])(.+?)\}\}/g;c.prototype.render=function(a){return d(this.t,a)};window.t=c})();

//性别map
var sexMap={"1":"男","2":"女","0":"未填"}

//对Date的扩展，将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
//例子： 
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
//(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
var week=["周日","周一","周二","周三","周四","周五","周六"];
 var o = {
     "M+": this.getMonth() + 1, //月份 
     "d+": this.getDate(), //日 
     "h+": this.getHours(), //小时 
     "m+": this.getMinutes(), //分 
     "s+": this.getSeconds(), //秒 
     "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
     "S": this.getMilliseconds(), //毫秒
     "W": week[this.getDay()] 
 };
 if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
 for (var k in o)
 if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
 return fmt;
}

/**
 * 根据路径得到文件名
 */
function getFileName(path){
	var pos1 = path.lastIndexOf('/');
	var pos2 = path.lastIndexOf('\\');
	var pos  = Math.max(pos1, pos2)
	if( pos<0 )
	return path;
	else
	return path.substring(pos+1);
	}

function path(args,p) {
    var result = [];
    for (var i = 0; i < args.length; i++){
    	var ra=[args[i].replace('@', p)];
    	alert(ra);
        result.push(ra);
    }
    	
    alert(result);
    return result
};
/**
 * 转换成日期格式 yyy-MM-dd
 */
function toDate(date,format){
	var result="";
	if(typeof date=="number"){
		result=new Date(date).Format(format?format:"yyyy-MM-dd");
	}else if(typeof date=="date"){
		result=date.Format(format?format:"yyyy-MM-dd");
	}
	return result;
}

/**
 * 转换成日期时间格式 yyy-MM-dd hh:mm:ss
 */
function toDateTime(date,format){
	var result="";
	if(typeof date=="number"){
		result=new Date(date).Format(format?format:"yyyy-MM-dd hh:mm:ss");
	}else if(typeof date=="date"){
		result=date.Format(format?format:"yyyy-MM-dd hh:mm:ss");
	}
	return result;
}
//创建一个loading append到body
function newLoading(){
	var loadingObj= $("#appLoading");
	if(loadingObj&&loadingObj.length==0){
		var loading='<div class="appLoading" style="display: none;" tabindex="-1" id="appLoading"><div class="loading-dialog">'
			+'<div class="loading-msg" id="appLoadingMsg">正在处理...</div><div class="loading-icon" id="appicon"></div></div></div>';
		$("body").append(loading);
	}
}
//创建一个formwaitting append到body
function newFormwaitting(form){
	 var formwaitting= $("#formwaitting");
	 if(formwaitting&&formwaitting.length==0){
		 var loading='<div class="appwaitting" style="display: none;" tabindex="-1" id="formwaitting"><div class="loading-dialog"><div class="loading-msg">正在提交，请稍后...</div><div class="loading-icon"></div></div></div>';
		 $("#"+form).before(loading);
	 }
}
//封装弹出loading
 function appLoading(msg,time){
	 newLoading();
	 if(msg&&msg.length>0){
	    	$("#appLoadingMsg").text(msg);
	    }
      $("#appicon").show();
      $("#appLoading").show();
      if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
      }
  }
 //封装弹出loading
 function appMsg(msg,time){
	 newLoading();
    if(msg&&msg.length>0){
    	$("#appLoadingMsg").text(msg);
    }
      $("#appicon").hide();
      $("#appLoading").show();
      if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
      }
  }
 //封装弹出loading
 function appErrorMsg(msg,time){
	 newLoading();
	 if(msg&&msg.length>0){
		 $("#appLoadingMsg").html("<span class='t-red font-20'><i class='glyphicon glyphicon-warning-sign pr10'></i>"+msg+"</span>");
	 }
	 $("#appicon").hide();
	 $("#appLoading").show();
	 if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
	 }
 }
 //封装弹出loading
 function appSuccessMsg(msg,time){
	 newLoading();
    if(msg&&msg.length>0){
    	$("#appLoadingMsg").html("<span class='t-green font-20'><i class='glyphicon glyphicon-ok pr10'></i>"+msg+"</span>");
    }
      $("#appicon").hide();
      $("#appLoading").show();
      if(time&&time>0){
		 setTimeout(function(){
			 $("#appLoading").hide();
		 },time);
      }
  }
 function closeAppLoading(){
	 setTimeout(function(){
		 $("#appLoading").hide();
	 },200);
 }
  function closeAppLoadingNow(){
      $("#appLoading").hide();
  }
  
  function waittingform(form,msg,parent){
	  newFormwaitting(form);
	  if(parent){
		  $("#"+parent).find("#"+form).hide();
	  }else{
		  $("#"+form).hide();
	  }
	  var waitting=$("#formwaitting");
		if(msg){
			waitting.find("div.loading-msg").text(msg);
		}
		waitting.show();
	  
  }
  function closeWaittingForm(form,parent){
	  setTimeout(function(){
		  if(parent){
			  $("#"+parent).find("#"+form).show();
		  }else{
			  $("#"+form).show();
		  }
		  $("#formwaitting").hide().remove();
	  }, 200);
  }
  
function waittingform_popover(form,msg){
		  newFormwaitting();
		  $("#"+form).hide();
		  var waitting=$("#formwaitting");
		if(msg){
			waitting.find("div.loading-msg").text(msg);
		}
		waitting.show();
		
}
function closeWaittingForm_popover(form){
		setTimeout(function(){
			$("#"+form).show();
			$("#formwaitting").hide().remove();
		}, 200);
	}
	/**
	 * 将指定form序列化到制定数据中 array
	 * @param data
	 * @param formId
	 */
	function fillSearchData(data,formId){
		var form=$("#"+formId);
		form.find("input[type='text'],select").each(function(i,obj){
			data[obj.name]=obj.value;
		});
		form.find("input[type='hidden']").each(function(i,obj){
			data[obj.name]=obj.value;
		});
		form.find("input[type='radio']:checked").each(function(i,obj){
			data[obj.name]=obj.value;
		});
		form.find("input[type='checkbox']:checked").each(function(i,obj){
			data[obj.name]=obj.value;
		});
	}

  /**
   * 设置select选中值
   * @param id
   * @param value
   */
  function setSelectValue(id,value){
	  $("#"+id).val(value?value:0);
  }
  /**
   * 设置radio选中值
   * @param id_front
   * @param value
   * @param defaultValue
   */
  function setRadioValue(id_front,value,defaultValue){
	  if(value){
    		$("#"+id_front+value).attr("checked","checked");
	  }else{
  	  		$("#"+id_front+defaultValue).attr("checked","checked");
	  }
  }
  
  
  /********************************************************************
   ************************表单验证 开始******************************
   ********************************************************************/  
    String.prototype.trim=function(){return this.replace(/(^\s*)|(\s*$)/g, "");}
    /**
     * 判断对象是否为array
     * @param obj
     * @returns {Boolean}
     */
    function isArray(obj){ 
    	return (typeof obj=='object')&&obj.constructor==Array; 
    } 

    var g = function (id) {
        return "string" == typeof id ? document.getElementById(id) : id;
    };
  //摇摆摇摆摇摆起来
    jQuery.fn.shake = function(intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
        this.each(function() {
            var jqNode = $(this);
            jqNode.css({position: 'relative'});
            for (var x=1; x<=intShakes; x++) {
                jqNode.animate({ left: (intDistance * -1) },(((intDuration / intShakes) / 4)))
                .animate({ left: intDistance },((intDuration/intShakes)/2))
                .animate({ left: 0 },(((intDuration/intShakes)/4)));
            }
        });
        return this;
    }

    //检查form表单中的input textarea select
    var checkInput=function(optform){
        var error=true;
        $("input,textarea,select",optform).each(function(){
            if(!error){
                return error;
            }
            var input=$(this);
            if(typeof(input.attr("check"))!="undefined"){
                var flag = checktype(input);
                var ok='<span class="glyphicon glyphicon-ok form-control-feedback"></span>';
                var remove='<span  class="glyphicon glyphicon-remove form-control-feedback"></span>';
                var next=input.next().hasClass("input-group-addon");
                var prev=input.prev().hasClass("input-group-addon");
                var ta=input.is("textarea");
                if (!flag) {
                	error=false;
                	if(ta){return;}
                	if(input.is("input")&&input.attr("type")=="hidden"){return;}
                	input.parents(".form-group").removeClass("has-success").addClass("has-error").addClass("has-feedback");
                	if(!next&&prev){
                		input.parents(".form-group").append(remove).find(".glyphicon-ok").remove();
                	}
                	if(!next&&!prev){
                		input.parent().append(remove).find(".glyphicon-ok").remove();
                	}
                    input.shake(2,10,400);
                    input.focus();
                }else{
                	error=true;
                	if(ta){return;}
                	if(input.is("input")&&input.attr("type")=="hidden"){return;}
                	input.parents(".form-group").removeClass("has-error").addClass("has-success").addClass("has-feedback");
                	if(!next&&prev){
                		input.parents(".form-group").append(ok).find(".glyphicon-remove").remove();
                	}
            		if(!next&&!prev){
	        			input.parent().append(ok).find(".glyphicon-remove").remove();
	        		}
                }
            }
        });
        return error;
    }
    //检查给定一个input textarea select的值
    function checktype(input) {
        var type=input.attr("check"),
         value=input.val(),
         mytips=input.attr("tips"),
          show=input.attr("show"),
          notNull=input.attr("notNull");
        if (show != null) {
            g(show).innerHTML = "";
        }
        //检测是否为空
    	if(typeof value=="string"){
    		value=value.trim();
    	}
            if (!value) {
                //检查配置是否需要进行非空检测
                if(notNull==null||notNull==true||notNull=="true"){
                        if(mytips!=null){
                            if (show == null) {
                            	appErrorMsg(mytips, 1000);
                            } else {
                                g(show).innerHTML = mytips;
                            }
                        }
                return false;
                }else{
                return true;
                }
             }
        return checkTypes(type,value,mytips,show,notNull);

    }
    //检测数据类型
    function checkTypes(type,value,mytips,show,notNull){
        //验证多个的时候
        var types=type.split("&");
        var checkFlag=true;
        var error=1;
        var success=2;
        var canNotCheck=3;
        for(var i=0;i<types.length;i++){
            var type=types[i];
            var checkResult=checkSelf(type,value,mytips,show,notNull);
            if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
                if(checkResult==success){
                    continue;
                }else{
                    checkFlag=false;
                    break;
                }
            }
            
            //如果上面不能处理 则进入比较处理
            checkResult=checkCompare(type,value,mytips,show,notNull);
            if(checkResult!=canNotCheck){//判断能否处理 如果处理了 成功了继续下一个type 失败了则直接整个结束
                if(checkResult==success){
                    continue;
                }else{
                    checkFlag=false;
                    break;
                }
            }
            
            
        }
        return checkFlag;
    }

    //检测比较
    function checkCompare(type,value,mytips,show,notNull){
        var error=1;
        var success=2;
        var canNotCheck=3;
        var selfValue=getRealTypeValue(value);
        var compareValue=getCompareValue(type);
        if(type.indexOf("len>=")!=-1){
            if(value.length>=compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }else if(type.indexOf(">=")!=-1){
        	if(selfValue>=compareValue){
        		return success;
        	}
        	showMyTipsIfNeed(mytips,show);
        	return error;
        }else if(type.indexOf("len<=")!=-1){
            if(value.length<=compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }else if(type.indexOf("<=")!=-1){
        	if(selfValue<=compareValue){
        		return success;
        	}
        	showMyTipsIfNeed(mytips,show);
        	return error;
        }else if(type.indexOf(">")!=-1){
            if(selfValue>compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }else if(type.indexOf("<")!=-1){
            if(selfValue<compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }else if(type.indexOf("!=")!=-1){
            if(selfValue!=compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }else if(type.indexOf("==")!=-1){
            if(selfValue==compareValue){
                return success;
            }
            showMyTipsIfNeed(mytips,show);
            return error;
        }

        return canNotCheck;
    }
    //得到正确类型的值
    function getRealTypeValue(value){
        if(!isNaN(value)){
            return Number(value);
        }
        return value;
    }
    //得到需要比较的值
    function getCompareValue(type){
        if(type.indexOf("#")!=-1){
            var cid=type.substring(type.indexOf("#"));
            return getRealTypeValue($(cid).val());
        }else{
        	if(type.indexOf("len")!=-1){
        		type=type.substring(3);
        	}
            if(type.indexOf("=")!=-1){
                return getRealTypeValue(type.substring(2));
            }else{
                return getRealTypeValue(type.substring(1));
            }
        }
    }
    //显示提示信息
    function showMyTipsIfNeed(mytips,show){
        if(mytips!=null){
                    if (show == null) {
                        alert(mytips);
                    } else {
                        g(show).innerHTML = mytips;
                    }
         }
    }
    //验证规则map
    var ruleMap=[
        {type:"double",method:function(value){return (!isNaN(value));}},//数字校验
        {type:"number",method:function(value){return (!isNaN(value));}},//数字校验
        {type:"pnumber",method:function(value){return (!isNaN(value)&&value*1>0);}},//验证正数
        {type:"int",method:function(value){return TestRgexp(/^-?[0-9]\d*$/, value);}},//整数校验
        {type:"pint",method:function(value){return TestRgexp(/^[0-9]*[1-9][0-9]*$/, value);}},//正整数校验
        {type:"email",method:function(value){return TestRgexp(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, value);}},//Email校验
        {type:"filepath",method:function(value){return TestRgexp(/^([a-zA-Z]){1}:(\\[^\/\\:\*\?\"<>]+)*(\\)?$/, value);}},//URL校验
        {type:"url",method:function(value){return TestRgexp(/^([a-zA-Z]){1}:(\\[^\/\\:\*\?\"<>]+)*(\\)?$/, value);}},//URL校验
        {type:"date",method:function(value){return TestRgexp(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/,value);}}//日期验证
    ];

    //检测自身
    function checkSelf(type,value,mytips,show,notNull){
        var error=1;
        var success=2;
        var canNotCheck=3;
        if(type=="string"){
            return success;
        }
        var process=false;
        for(var i=0;i<ruleMap.length;i++){
            if(type==ruleMap[i].type){
                process=true;
                var result=ruleMap[i].method.call(this,value);
                if (!result) {
                    showMyTipsIfNeed(mytips,show);
                    return error;
                }
            }
        }
        return process?success:canNotCheck;
     
        
    }
    //调用正则表达式验证
    function TestRgexp(re, s) {
        return re.test(s);
    }

    /********************************************************************
     ************************表单验证 结束******************************
     ********************************************************************/  

    //弹出pop的模板文件
    var pop_tplhtml='<div id="popover_{{=id}}" refreshBtnId="{{=refreshBtnId}}" class="popover {{=dir}}"><div class="arrow"></div><h3 class="popover-title">{{=title}}<button  type="button" class="close pull-right" ><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button></h3><div class="popover-content"><center><img src="assets/css/imgs/loadingurl.gif"/></center></div></div>';
    function openPopover(popSetting,btnTarget,refreshBtnId){
    	var id=btnTarget.id;
    	popSetting.id=id;
    	popSetting.refreshBtnId=refreshBtnId;
    	var popover=$("#popover_"+id);
    	if(popover&&popover.length>0){
    		popover.show();
    		return;
    	}else{
    		var pop_tpl=new t(pop_tplhtml);
        	var popHtml=pop_tpl.render(popSetting);
        	$("body").append(popHtml);
        	popover=$("#popover_"+id);
    	}
    	var popContent=popover.find("div.popover-content");
    	popContent.empty();
    	popover.css("max-width","auto")
				    	.css("min-width","250px")
				    	.css("max-width",popSetting.width?popSetting.width:"600px")
				    	.css("width",popSetting.width?popSetting.width:"350px")
				    	.css("height","auto");
    	var height=popover.height();
    	var targetloc=$(btnTarget).offset();
    	var left=targetloc.left+20;
    	var top=targetloc.top-35;
    	popover.find("button.close").click(function(){
    		popover.remove();
    	});
    	popover.find("div.arrow").css("top","43px");
    	popover.css("top",top).css("left",left);
    	var url=popSetting.url;
    	if(url.indexOf("?")!=-1){
    		url+="&rand="+new Date().getTime();
    	}else{
    		url+="?rand="+new Date().getTime();
    	}
    	$.get(popSetting.url,function(data){
    		popContent.html(data);
    		popover.show();
    	});
    	
    }
    
    /**
     * 创建操作列 editbutton
     * @param btnSetting
     */
    function addEditButton(btnSetting){
    	if(!btnSetting.title){
    		btnSetting.title="修改";
    	}
    	if(!btnSetting.href){
    		btnSetting.href="javascript:void(0)";
    	}
    	var button_tpl ='<a class="editBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}"><img src="assets/css/imgs/update.png" align="absmiddle"></a>&nbsp;';
    	var button_noimg_tpl ='<a class="editBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}">{{=title}}</a>&nbsp;';
    	
    	var btn_tpl=new t(btnSetting.img?button_tpl:button_noimg_tpl);
    	return  btn_tpl.render(btnSetting);
    }
    /**
     * 创建操作列 delbutton
     * @param btnSetting
     */
    function addDelButton(btnSetting){
    	if(!btnSetting.title){
    		btnSetting.title="删除";
    	}
    	if(!btnSetting.href){
    		btnSetting.href="javascript:void(0)";
    	}
    	var button_tpl ='<a class="delBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}"><img src="assets/css/imgs/delete.png" align="absmiddle"></a>&nbsp;';
    	var button_noimg_tpl ='<a class="delBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}">{{=title}}</a>&nbsp;';
    	
    	var btn_tpl=new t(btnSetting.img?button_tpl:button_noimg_tpl);
    	return  btn_tpl.render(btnSetting);
    }
    /**
     * 创建操作列 detailbutton
     * @param btnSetting
     */
    function addDetailButton(btnSetting){
    	if(!btnSetting.title){
    		btnSetting.title="详情";
    	}
    	if(!btnSetting.href){
    		btnSetting.href="javascript:void(0)";
    	}
    	var button_tpl ='<a class="detailBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}"><img src="assets/css/imgs/info.png" align="absmiddle"></a>&nbsp;';
    	var button_noimg_tpl ='<a class="detailBtn {{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}">{{=title}}</a>&nbsp;';
    	
    	var btn_tpl=new t(btnSetting.img?button_tpl:button_noimg_tpl);
    	return  btn_tpl.render(btnSetting);
    }
    /**
     * 创建操作列 button
     * @param btnSetting
     */
    function addOptButton(btnSetting){
    	if(!btnSetting.title){
    		btnSetting.title="按钮";
    	}
    	if(!btnSetting.href){
    		btnSetting.href="javascript:void(0)";
    	}
    	var button_tpl ='<a class="{{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}"><img src="{{=imgUrl}}" align="absmiddle"></a>&nbsp;';
    	var button_noimg_tpl ='<a class="{{=class}}" objId="{{=objId}}" href="{{=href}}" title="{{=title}}">{{=title}}</a>&nbsp;';
    	
    	var btn_tpl=new t(btnSetting.img?button_tpl:button_noimg_tpl);
    	return  btn_tpl.render(btnSetting);
    }
    
    function addDropDownButton(btnSetting){
    	var divider='<li class="divider"></li>';
    	var btn='<li><a href="javaecript:void(0)" objId="{{=objId}}"  class="{{=class}}">{{=title}}</a></li>';
    	var btnhtml='<div class="btn-group">'
    		    +'<button type="button" class="btn btn-default dropdown-toggle {{=class}}" data-toggle="dropdown">'
    		    +' {{=title}} <span class="caret"></span></button>'
    		    +'<ul class="dropdown-menu" role="menu">';
    	var btns_tpl=new t(btnhtml);
    	if(!btnSetting.class){btnSetting.class="btn-sm"};
    	btnhtml=btns_tpl.render({class:btnSetting.class,title:btnSetting.title});
    	var btns=btnSetting.btns;
    	if(btns&&btns.length>0){
    		var btn_tpl=new t(btn);
    		var btnType=null;
    		var temp_btn=null;
    		for(var i=0;i<btns.length;i++ ){
    			var temp_btn=btns[i];
    			if(temp_btn.type&&temp_btn.type=="divider"){
    				btnhtml+=divider;
    			}else{
    				btnhtml+=btn_tpl.render(btns[i]);
    				console.log(btnhtml);
    			}
    		}
    	}
    	btnhtml+="</ul></div>";
    	return btnhtml;
    	
    }
    
    /**
     * 弹出modal
     * @param windowSetting
     */
    function openModal(modalSetting){
    	if(!modalSetting.id){
    		alert("请指定弹出modal的id");
    		return;
    	}
    	var modal=$("#modal_"+modalSetting.id);
    	if(modal&&modal.length>0){
    		modal.remove();
    	}
    	if(!modalSetting.url){
    		alert("请指定弹出modal的url");
    		return;
    	}else{
    		if(modalSetting.url.indexOf("?")!=-1){
    			modalSetting.url+="&rand="+new Date().getTime();
    		}else{
    			modalSetting.url+="?rand="+new Date().getTime();
    		}
    	}
    	if(modalSetting.type){
    		if(modalSetting.type=="sm"){
    			modalSetting.type="modal-sm";
    		}else if(modalSetting.type=="lg"){
    			modalSetting.type="modal-lg";
    		}
    	}
    	
    	
    	if(modalSetting.height&&modalSetting.height!="auto"&&!isNaN(modalSetting.height)){
    		modalSetting.height+="px";
    	}
    	
    	
    	var modal_ajax='<div class="modal fade" id="modal_{{=id}}"><div id="modalDialog_{{=id}}" class="modal-dialog {{=type}}">'
    		+'<div class="modal-content"><div class="modal-header">'
    		+'<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'
    		+'<h4 class="modal-title">{{=title}}</h4></div>'
    		+'<div class="modal-body {{=bodyClass}}" style="height:{{=height}};overflow-y:auto;" id="modalHtml_{{=id}}">&nbsp;</div>'
    		+'<div class="modal-footer"  id="modal_footer_{{=id}}">'
    		+'<button type="button" class="btn btn-primary hide" id="submitModalBtn_{{=id}}">提交</button>'
    		+'<button type="button" class="btn btn-default hide" id="closeModalBtn_{{=id}}" data-dismiss="modal">关闭</button>'
    		+'</div></div></div></div>';
    	var modal_iframe='<div class="modal fade" id="modal_{{=id}}"><div id="modalDialog_{{=id}}" class="modal-dialog {{=type}}">'
    		+'<div class="modal-content"><div class="modal-header">'
    		+'<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>'
    		+'<h4 class="modal-title">{{=title}}</h4></div>'
    		+'<div class="modal-body" style="height:{{=height}};padding:0px;" id="modalHtml_{{=id}}">'
    		+'<iframe id="iframe_{{=id}}" src="{{=url}}" frameborder="no" allowtransparency="true" scrolling="auto" style="width: 100%; height: 100%; left: 0px;"></iframe>'
    		+'</div><div class="modal-footer" id="modal_footer_{{=id}}">'
    		+'<button type="button" class="btn btn-primary hide" id="submitModalBtn_{{=id}}">提交</button>'
    		+'<button type="button" class="btn btn-default hide" id="closeModalBtn_{{=id}}" data-dismiss="modal">关闭</button>'
    		+'</div></div></div></div>';
    	var modal_html="";
    	var modal_tpl=null;
    	if(modalSetting.loadType=="iframe"){
    		modal_tpl=new t(modal_iframe);
        	modal_html=modal_tpl.render(modalSetting);
    	}else{
    		modal_tpl=new t(modal_ajax);
        	modal_html=modal_tpl.render(modalSetting);
    	}
    	$("body").append(modal_html);
    	modal=$("#modal_"+modalSetting.id);
    	if(modalSetting.width){
    		$("#modalDialog_"+modalSetting.id).css("width",modalSetting.width);
    	}
    	if(modalSetting.footer){
    		if(modalSetting.footer.submit){
    			$("#submitModalBtn_"+modalSetting.id).removeClass("hide");
    			if(modalSetting.footer.submit.event){
    				$("#submitModalBtn_"+modalSetting.id).click(modalSetting.footer.submit.event);
    			}
    			if(modalSetting.footer.submit.text){
    				$("#submitModalBtn_"+modalSetting.id).text(modalSetting.footer.submit.text);
    			}
    		}
    		if(modalSetting.footer.close){
    			$("#closeModalBtn_"+modalSetting.id).removeClass("hide");
    			if(modalSetting.footer.close.event){
    				$("#closeModalBtn_"+modalSetting.id).click(function(){
    					modalSetting.footer.close.event();
    					return false;
    				});
    			}
    			if(modalSetting.footer.close.text){
    				$("#closeModalBtn_"+modalSetting.id).text(modalSetting.footer.close.text);
    			}
    		}
    	}else{
    		$("#modal_footer_"+modalSetting.id).empty();
    	}
    	if(modalSetting.loadType=="ajax"){
    		appLoading("正在加载,请稍后...");
			$.get(modalSetting.url,function(data){
				closeAppLoadingNow();
				$("#modalHtml_"+modalSetting.id).html(data);
				if(modalSetting.autoClose){
	    			modal.modal("show");
	    		}else{
	    			modal.modal({backdrop: 'static', keyboard: false});
	    		}
				autoLoadSelect({parent:"modalHtml_"+modalSetting.id});
				$('[data-toggle="tooltip"]',"#modalHtml_"+modalSetting.id).tooltip();
				if(window.initPage){
					window.initPage();
				}
				if(modalSetting.initCallback){
	    			modalSetting.initCallback();
	    		}
			});
    	}else{
    		if(modalSetting.autoClose){
    			modal.modal("show");
    		}else{
    			modal.modal({backdrop: 'static', keyboard: false});
    		}
    		if(modalSetting.initCallback){
    			modalSetting.initCallback();
    		}
    	}
    	//隐藏后就删掉 防止多框冲突
    	modal.on('hidden.bs.modal', function (e) {
    		if(modalSetting.closeCallback){
    			modalSetting.closeCallback();
    		}
    		  modal.remove();
    		});
    }
    /**
     * 验证
     * @param el
     * @returns 
     */
    function validateMe(el) {
    	var retValue = {};
    	var input=$(el);
    	var tag=input.prop("tagName");
    	if(tag=="TEXTAREA"&&input.hasClass("useeditor")){
    		if(!input.val()){
    			retValue.status=false;
    			appErrorMsg("请输入内容", 1000);
    		}
    		
    	}else{
	    	var flag=checktype(input);
	    	var ok='<span class="glyphicon glyphicon-ok form-control-feedback"></span>';
	        var remove='<span  class="glyphicon glyphicon-remove form-control-feedback"></span>';
	        var next=input.next().hasClass("input-group-addon");
	        var prev=input.prev().hasClass("input-group-addon");
	        if (!flag) {
	        	retValue.status=false;
	        	if(input.is("input")&&input.attr("type")=="hidden"){return;}
	        		input.parents(".form-group").removeClass("has-success").addClass("has-error").addClass("has-feedback");
	        		if(!next&&prev){
	        			input.parents(".form-group").append(remove).find(".glyphicon-ok").remove();
	        		}
	        		if(!next&&!prev){
	                    input.parent().append(remove).find(".glyphicon-ok").remove();
	        		}
	            input.shake(2,10,400);
	            input.focus();
	        }else{
	        	retValue.status=true;
	        	if(input.is("input")&&input.attr("type")=="hidden"){return;}
	        	input.parents(".form-group").removeClass("has-error").addClass("has-success").addClass("has-feedback");
	        	if(!next&&prev){
	        		input.parents(".form-group").append(ok).find(".glyphicon-remove").remove();
	        	}
	        	if(!next&&!prev){
	        		input.parent().append(ok).find(".glyphicon-remove").remove();
	        	}
	        	
	        }
    	}
	    return retValue;
	}
    /**
     * 打开wizard
     * @param wizardSetting
     */
    function openWizard(wizardSetting){
    	if(!wizardSetting.id){
    		alert("请指定弹出Wizard的id");
    		return;
    	}
    	var wizardId="wizard_"+wizardSetting.id;
    	var wizard=$("#"+wizardId);
    	if(wizard&&wizard.length>0){
    		wizard.remove();
    	}
    	if(!wizardSetting.url){
    		alert("请指定弹出Wizard的url");
    		return;
    	}else{
    		if(wizardSetting.url.indexOf("?")!=-1){
    			wizardSetting.url+="&rand="+new Date().getTime();
    		}else{
    			wizardSetting.url+="?rand="+new Date().getTime();
    		}
    	}
    	if(!wizardSetting.submitUrl){
    		alert("请指定弹出Wizard的url");
    		return;
    	}else{
    		if(wizardSetting.submitUrl.indexOf("?")!=-1){
    			wizardSetting.submitUrl+="&rand="+new Date().getTime();
    		}else{
    			wizardSetting.submitUrl+="?rand="+new Date().getTime();
    		}
    	}
    	appLoading("正在加载...");
    	//异步读取url指定的页面后弹出
    	$.get(wizardSetting.url,function(data){
    		var wizardHtml=$(data);
    		if(wizardHtml.hasClass("error")){
    			closeAppLoadingNow();
    			appErrorMsg("读取异常",1000);
    			return false;
    		}
    		
    		wizardHtml.attr("id",wizardId);
    		$("body").append(wizardHtml);
    		//弹出wizard
    		wizard = $("#"+wizardId).wizard({
    			keyboard : false,
    			showCancel:true,
    			contentHeight : wizardSetting.height,
    			contentWidth : wizardSetting.width,
    			backdrop: 'static',
    			buttons: {
    	                cancelText: "取消",
    	                nextText: "下一步",
    	                backText: "上一步",
    	                submitText: "提交",
    	                submittingText: "提交中...",
    	            },
    	            submitUrl:wizardSetting.submitUrl
    		});
    		//初始化wizard后需要调用callback
        	if(wizardSetting.initCallback){
        		wizardSetting.initCallback();
        	}
        	$("div.wizard").find("form").first().attr("id",wizardId+"_form");
        	//调用显示
        	wizard.show();
        	closeAppLoading();
        	//隐藏后就删掉 防止多框冲突
        	wizard.on("closed", function () {
        		$("#"+wizardId).remove();
        		$("div.wizard").remove();
        		//初始化wizard后需要调用callback
            	if(wizardSetting.closeCallback){
            		wizardSetting.closeCallback();
            	}
        	});
        	wizard.on("submit", function(wizard){
        		waittingform(wizardId+"_form");
        		wizard._submitting=false;
        		wizard.hideButtons();
        		 $.ajax({
				        type: "POST",
				        url: wizard.args.submitUrl,
				        data: wizard.serialize(),
				        dataType: "json"
				    }).done(function(response) {
				    	closeWaittingForm(wizardId+"_form");
				    	if(response.success){
				    		 wizard.el.find("#errorAlert").hide();
					        wizard.submitSuccess();
				    	}else{
				    	   wizard.enableNextButton();
				    	   wizard.changeNextButton("提交","btn-success");
				    	   wizard.showButtons();
				    	   wizard.el.find("#errorAlert").show().find("strong").text(response.msg);
				    	}
				    }).fail(function() {
				    	   closeWaittingForm(wizardId+"_form");
				    	   wizard.enableNextButton();
				    	   wizard.changeNextButton("提交","btn-success");
				    	   wizard.showButtons();
				    	   wizard.el.find("#errorAlert").show().find("strong").text("数据提交异常，可能网络中断");
				    });
        	});
        	wizard.on("reset", function() {
        		if(wizard.resetForm){
        			wizard.modal.find('div.button-next').removeAttr('disabled');
            		wizard.modal.find("input,select").parents(".form-group").removeClass("has-error").removeClass("has-success").removeClass("has-feedback").find(".glyphicon-remove,.glyphicon-ok").remove();
            		$("#"+wizardId+"_form")[0].reset();
            		if(wizardSetting.resetCallback){
            			wizardSetting.resetCallback();
            		}
        		}
        		
			});
        	wizard.el.find(".wizard-success .im-done").click(function() {
            	$("#"+wizardId).remove();
        		$("div.wizard").remove();
        		//初始化wizard后需要调用callback
        		if(wizardSetting.closeCallback){
        			wizardSetting.closeCallback();
        		}
            	if(wizardSetting.submitSuccessCallback){
            		wizardSetting.submitSuccessCallback();
            	}
				
			});
		
        	wizard.el.find(".wizard-success .create-another").click(function() {
        		wizard.resetForm=true;
        		wizard.reset();
        	});
			wizard.el.find(".wizard-success .remodify").click(function() {
				wizard.resetForm=false;
				wizard.reset();
			});
    	});
    	
    	
    	return wizard;
    	
    }
    
    
/********************************************************************
 ************************自动化组件封装******************************
 ********************************************************************/  
/**
 * 处理select
 * setting selectId parentId callback
 */
function autoLoadSelect(setting){
	var selectModal='{{@result}}<option value="{{=_val.optionValue}}">{{=_val.optionText}}</option>{{/@result}}';
	var template = new t(selectModal);
	var insert=function(_this,refreshing){
		var selectedValue=_this.attr("selectValue");
		if(refreshing){
			selectedValue=_this.val();
		}
		_this.empty();
		if(_this.attr("firstText")){
			_this.append('<option value="'+_this.attr("firstValue")+'">'+_this.attr("firstText")+'</option>');
		}
		var url=_this.attr("url");
		$.ajax({
			type:"GET",
			url:url,
			dataType:"json",
			context:_this,
			success:function(result){
				if(refreshing){
					closeAppLoading();
				}
				if(result.success){
					var html = template.render(result);
					_this.append(html);
					_this.val(selectedValue);
				}
				if(setting&&setting.callback){
					setting.callback();
				}
			}
		});
	}
	var select;
	if(setting){
		if(setting.selectId){
			if(setting.parent){
				select=$("#"+setting.parent).find("#"+setting.selectId);
			}else{
				select=$("#"+setting.selectId);
			}
			
		}else{
			if(setting.parent){
				select=$("#"+setting.parent).find("select.autoLoad"); 
			}else{
				select=$("select.autoLoad"); 
			}
		}
	}else{
		select=$("select.autoLoad");
	}
	select.each(function(i,obj){
		var _this=$(obj);
		insert(_this);
		if(_this.hasClass("refresh")){
			var refreshBtn=document.createElement("div");
			refreshBtn.className="input-group-addon handcursor";
			refreshBtn.innerHTML='<span class="glyphicon glyphicon-refresh"></span>';
			$(refreshBtn).click(function(){
				appLoading("正在刷新数据...");
				insert(_this,true);
			});
			obj.parentElement.appendChild(refreshBtn);
		}
	});
}
/**
 * 处理列表panel
 */
function autoLoadPanelListGroup(panelId){
	var refreshBtn='<div id="{{=panelId}}_btnGroup" class="btn-group btn-group-xs ml10" role="group"><button id="{{=panelId}}_refreshBtn" type="button" class="btn btn-default refreshBtn"><span class="glyphicon glyphicon-refresh"></span></button></div>';
	var addBtnModal='<button id="{{=panelId}}_addBtn" type="button" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span></button>';
	var listModal='{{@result}}<li id="{{=_val.panelId}}_{{=_val.optionValue}}" class="list-group-item">{{=_val.optionText}}</li>{{/@result}}';
	var listModal_del='{{@result}}<li id="{{=panelId}}_{{=_val.optionValue}}" class="list-group-item">{{=_val.optionText}}<button objId="{{=_val.optionValue}}" type="button" class="close" ><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button></li>{{/@result}}';
	var template_refreshBtn = new t(refreshBtn);
	var template_addBtn = new t(addBtnModal);
	var template = new t(listModal);
	var template_del = new t(listModal_del);
	function insert(_this,panelId,refreshing){
		var group=_this.find("ul.list-group").first();
		if(!group){alert("panel list-group不存在");return;}
        var url=_this.attr("url");
        if(!url){alert("请填写panel 数据的获取url");return;}
        group.empty();
        $.ajax({
            type:"GET",
            url:url,
            dataType:"json",
            context:_this,
            success:function(result){
            	if(refreshing){
            		closeAppLoading();
            	}
            	if(result.success){
	            	result.panelId=panelId;
	            	var html="";
	            	if(_this.hasClass("delete")){
	            		html= template_del.render(result);
	            	}else{
	            		html= template.render(result);
	            	}
	            	group.append(html);
            	}
            }
        });
        
       
	}
		//获取自动加载数据的panel 一个页面可以能多个
        var listGroup= $(panelId?"#"+panelId:"div.panel.autoLoad");
        listGroup.each(function(i,obj){
        	var _this=$(obj);
        	var panelId=_this.attr("id");
        	if(!panelId){alert("请为显示数据的panel赋值ID");return;}
        	insert(_this,panelId);
        	_this.find("div.panel-heading").append(template_refreshBtn.render({panelId:panelId}));
        	$("#"+panelId+"_refreshBtn").click(function(){
        		$("#popover_"+panelId+"_addBtn").remove();
        		appLoading("正在刷新数据...");
				insert(_this,panelId,true);
			});
        	//添加按钮绑定事件
            if(_this.hasClass("add")){
            	var initAddUrl=_this.attr("addUrl");
            	if(!initAddUrl){alert("请为panel的数据添加addUrl"); return;}
            	$("#"+panelId+"_btnGroup").prepend(template_addBtn.render({panelId:panelId}));
            	$("#"+panelId+"_addBtn").click(function(){
    				var url="challengeCategory/initAdd?rand="+new Date().getTime();
    				openPopover({
    					url:url,
    					dir:"right",
    					title:"新增",
    					content:"新增谁"
    				},this,panelId+"_refreshBtn");
            	});
            }
            //添加删除事件处理
            if(_this.hasClass("delete")){
            	var delUrl=_this.attr("delUrl");
            	 _this.on("click","button.close",function(){
                 	if(confirm("确定删除吗？")){
                 		appLoading("正在执行删除，请稍后...");
                 		var objId=$(this).attr("objId");
                 		$.ajax({
                 			url:delUrl,
                 			type:"post",
                 			data:{id:objId},
                 			dataType:"json",
                 			success:function(result){
                 				closeAppLoadingNow();
                 				if(result.success){
                 					$("#"+panelId+"_"+objId).remove();
                 					appSuccessMsg("删除成功", 1000);
                 				}else{
                 					appErrorMsg(result.msg, 1000);
                 				}
                 			}
                 		});
                 	}
                 });
            }
        });
    }
//处理全局自动处理的组件和事件
$(function(){
	//自动加载数据的select
	autoLoadSelect();
	//自动加载数据的panel list
	autoLoadPanelListGroup();
	$(".table").on("click","tbody tr",function () {
		 $(this).parents('tbody').find('tr.selected').removeClass('selected');
         $(this).addClass('selected');
	});
	$('[data-toggle="tooltip"]').tooltip();
});
    
    